﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 订单应用服务类
    /// </summary>
    public class OrderAppService : ApplicationService, IOrderAppService
    {
        private readonly IRepository<Order, int> _orderRepository;

        public OrderAppService(
            IRepository<Order, int> orderRepository)
        {
            _orderRepository = orderRepository;
        }

        // 分页列表
        public async Task<ListResponse<OrderDto>> PagedListAsync(
            PagedListRequest request,
            string name = null,
            string orderNo = null,
            string orderStatus = null,
            string orderType = null,
            string payTime = null)
        {
            // 查询
            var query = _orderRepository
                .WhereIf(!string.IsNullOrWhiteSpace(name), m => m.Name == name)
                .WhereIf(!string.IsNullOrWhiteSpace(orderNo), m => m.No == orderNo)
                .WhereIf(!string.IsNullOrWhiteSpace(orderStatus), m => m.Status == (OrderStatus)Enum.Parse(typeof(OrderStatus), orderStatus))
                .WhereIf(!string.IsNullOrWhiteSpace(orderType), m => m.Type == orderType)
                .WhereIf(!string.IsNullOrWhiteSpace(payTime), m => m.PayTime == DateTime.Parse(payTime))
                .AsQueryable();
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Order>, List<OrderDto>>(list);
            return ListResponse<OrderDto>.Successful(count, dtos);
        }
    }
}